//
//  FriendViewController.m
//  HappyStore
//
//  Created by pzx on 16/5/9.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "FriendViewController.h"
#import "thirdPersonVC.h"
#import "goveDetailVC.h"
#import "putDynamicVC.h"
#import "putDynamicDetailVC.h"
static NSMutableArray *dataArr;
@interface FriendViewController ()<UISearchBarDelegate>{
    
    NSInteger page;
    NSString *strTitle;
}
@property (weak, nonatomic) IBOutlet UISearchBar *searchbar;

@end

@implementation FriendViewController


-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
        
        NSArray *list=self.navigationController.navigationBar.subviews;
        
        for (id obj in list) {
            
            if ([obj isKindOfClass:[UIImageView class]]) {
                
                UIImageView *imageView=(UIImageView *)obj;
                
                NSArray *list2=imageView.subviews;
                
                for (id obj2 in list2) {
                    
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        
                        UIImageView *imageView2=(UIImageView *)obj2;
                        
                        imageView2.hidden=YES;
                        
                    }
                    
                }
                
            }
            
        }
        
    }
    
    if (self.TagerUserId) {
        self.tableView.y = 0;
        self.tableView.height = screenH - 60;
        self.tabBarController.tabBar.hidden = YES;
        [self endLoadMore];
        
    }else{
        
        self.tabBarController.tabBar.hidden = NO;
        
    }
    
    self.navigationController.navigationBarHidden = NO;
    //    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:19.0f],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    

    //找出导航栏的下边的黑线
    UIImageView *navBarHairlineImageView = [NaviBarLine findHairlineImageViewUnder:self.navigationController.navigationBar];
    navBarHairlineImageView.hidden = YES;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    
    // 设置刷新图片
    UIImage *images = [UIImage imageNamed:@"mj_footer"];
    NSArray *refreshingImages = @[images];
    [footer setImages:refreshingImages forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多内容了" forState:MJRefreshStateRefreshing];
    footer.stateLabel.font = [UIFont systemFontOfSize:12.0f];
    footer.stateLabel.textColor = [UIColor colorWithWhite:0.6 alpha:1.0f];
    
    [footer setAutomaticallyRefresh:NO];
    
    self.tableView.mj_footer = footer;
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];

}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"商务圈";
    
    self.searchbar.delegate = self;
    
    if (!self.TagerUserId) {
        
        UIBarButtonItem *rightItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"tianji" highImage:@"tianji"];
        self.navigationItem.rightBarButtonItem = rightItem;
        
        UIImage *selectedImgitemHome = [UIImage imageNamed:@"swq"];
        selectedImgitemHome = [selectedImgitemHome imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [self.navigationController.tabBarItem setSelectedImage:selectedImgitemHome];
        
    }
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    
    // 设置刷新图片
    UIImage *images = [UIImage imageNamed:@"mj_footer"];
    NSArray *refreshingImages = @[images];
    [footer setImages:refreshingImages forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多内容了" forState:MJRefreshStateRefreshing];
    footer.stateLabel.font = [UIFont systemFontOfSize:12.0f];
    footer.stateLabel.textColor = [UIColor colorWithWhite:0.6 alpha:1.0f];
    
    [footer setAutomaticallyRefresh:NO];
    
    self.tableView.mj_footer = footer;
    
    self.navigationController.tabBarItem.title = @"";
    
    
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.edgesForExtendedLayout = UIRectEdgeBottom | UIRectEdgeLeft | UIRectEdgeRight;
    
    self.tableView.y = self.tableView.y + 44;
    self.tableView.height = screenH - 60 - 46;
    
}

-(void)leftBarButtonItemClick{
    
    if (allConstMemberid) {
        
        putDynamicVC * putDynamic =[[putDynamicVC alloc]init];
        [self.navigationController pushViewController:putDynamic animated:YES];
        
    }else{
        
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        [alert show];
        
    }
    
}

-(void) initData
{
    
    for (NSDictionary * dict  in dataArr) {
        
        DFTextImageLineItem *textImageItem = [[DFTextImageLineItem alloc] init];
        textImageItem.itemType = LineItemTypeTextImage;
        
        textImageItem.zanCount = dict[@"zanCount"];
        textImageItem.shareCount = dict[@"shareCount"];
        textImageItem.commentCount = dict[@"commentCount"];
        textImageItem.resId = dict[@"Id"];
        textImageItem.isZan = dict[@"isZan"];
        textImageItem.userType = dict[@"userType"];
        //会员
        textImageItem.authState = dict[@"vipLevel"];
        textImageItem.isAuthState = dict[@"authState"];
        if ([dict[@"userType"] isEqualToString:@"3"]) {
            
            textImageItem.companyName = dict[@"address"];
            
        }else if ([dict[@"userType"] isEqualToString:@"1"]){
            
            if (![dict[@"companyUserName"] isEqualToString:@"null"] && ![dict[@"companyUserName"] isEqualToString:@""]) {
                
                textImageItem.companyName = dict[@"companyUserName"];
                
            }else{
                
                textImageItem.companyName = @"";
                
            }
            
        }else{
            
            textImageItem.companyName = @"";
            
        }
        
        textImageItem.userId = [dict[@"userId"] integerValue];
        textImageItem.userAvatar = dict[@"headPhoto"];
        textImageItem.userNick = dict[@"username"];
        
        if ([dict[@"posiTionName"] isEqualToString:@""] || [dict[@"posiTionName"] isEqualToString:@"null"]) {
            textImageItem.title = @"发表了";
        }else{
            textImageItem.title = dict[@"posiTionName"];
        }
        textImageItem.text = dict[@"content"];
        NSMutableArray *srcImages = [NSMutableArray array];
        NSMutableArray *thumbImages = [NSMutableArray array];
        NSArray * photoArr = dict[@"photos"];
        
        for (int i = 0 ; i < photoArr.count; i++) {
            
            NSString *str1 = photoArr[i];
            
            if (![str1 isEqualToString:Default_Image]) {

                [srcImages addObject:photoArr[i]];
                [thumbImages addObject:photoArr[i]];
                textImageItem.srcImages = srcImages;
                textImageItem.thumbImages = thumbImages;
            }
            
        }
        textImageItem.ts = dict[@"createTime"];
        
        if (photoArr.count == 1) {
            //显示单张图片时，固定高度；
            CGFloat itemH = 160;
            CGFloat itemW = 0;
            UIImageView *imageview = [[UIImageView alloc] init];
            NSURL *url = [NSURL URLWithString:photoArr[0]];
            [imageview sd_setImageWithURL:url];
            SDWebImageManager *manager = [SDWebImageManager sharedManager];
            //判断是否有缓存
            BOOL existBool = [manager diskImageExistsForURL:url];
            UIImage *image;
            if (existBool) {
                image = [[manager imageCache] imageFromDiskCacheForKey:url.absoluteString];
            }else{
                NSData *data = [NSData dataWithContentsOfURL:url];
                image = [UIImage imageWithData:data];
            }
            
            //根据image的比例来设置高度
            if (image.size.height) {
                itemW = image.size.width/image.size.height *itemH;
                if(itemW >= itemH){
                    itemW = 160;
                    itemH = image.size.height/image.size.width *itemW;
                }
            }
            
            textImageItem.width = itemW;
            textImageItem.height = itemH;
        }
    
        [self addItem:textImageItem];
    }
    
    [self endRefresh];
    //    textImageItem3.location = @"广州 ";
    
}



-(void)onLike:(long long)itemId
{
    //点赞
    NSLog(@"onLike: %lld", itemId);
    
    DFLineLikeItem *likeItem = [[DFLineLikeItem alloc] init];
    likeItem.userId = 10092;
    likeItem.userNick = @"亦非";
    [self addLikeItem:likeItem itemId:itemId];
    
}

-(void)onClickUser:(NSUInteger)userId userType:(NSString *)userType
{
    //点击左边头像 或者 点击评论和赞的用户昵称
    NSLog(@"onClickUser: %ld", (unsigned long)userId);
    
    if (!self.TagerUserId) {
        
        if ([userType isEqualToString:@"3"]) {
            
            goveDetailVC * goveDetail = [[goveDetailVC alloc]init];
            goveDetail.userType = userType;
            goveDetail.userId = [NSString stringWithFormat:@"%lu",(unsigned long)userId];
            self.tabBarController.tabBar.hidden = YES;
            [self.navigationController pushViewController:goveDetail animated:YES];
            
        }else{
            
            thirdPersonVC * thirdPerson = [[thirdPersonVC alloc]init];
            thirdPerson.userId = [NSString stringWithFormat:@"%lu",(unsigned long)userId];
            thirdPerson.userType = userType;
            self.tabBarController.tabBar.hidden = YES;
            [self.navigationController pushViewController:thirdPerson animated:YES];
            
        }
        
    }
    
    
    //    UserTimelineViewController *controller = [[UserTimelineViewController alloc] init];
    //    [self.navigationController pushViewController:controller animated:YES];
}
//分享
-(void)onClickUserShare:(NSUInteger)userId{
    [ShareMsg shareMsgBOOLType:YES titleStr:nil contentStr:nil urlStr:nil imageAry:nil];
}

-(void)onClickUserZan:(NSUInteger)userId{
    NSLog(@"关注: %ld", (unsigned long)userId);
}


-(void)onClickUserCot:(NSUInteger)userId userResid:(NSString *)userResid{
    NSLog(@"评论: %ld", (unsigned long)userId);
    
    NSDictionary * dataDict = [NSDictionary dictionary];
    
    for (NSDictionary * dict  in dataArr) {
        
        if ([dict[@"Id"] isEqualToString:userResid]) {
            dataDict = dict;
        }
        
    }
//        NSString * jsonStr = [LSHttpTool DataTOjsonString:dataDict];
//                    NSLog(@"--------------------json:%@",jsonStr);
    
    putDynamicDetailVC * putDynamicDetail = [[putDynamicDetailVC alloc]init];
    putDynamicDetail.dataDict = dataDict;
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:putDynamicDetail animated:YES];
}

-(void)onClickHeaderUserAvatar
{
    [self onClickUser:1111 userType:@"1111"];
}






-(void) refresh
{
    //下来刷新
    //模拟网络请求
    //    dispatch_time_t time=dispatch_time(DISPATCH_TIME_NOW, 2*NSEC_PER_SEC);
    //    dispatch_after(time, dispatch_get_main_queue(), ^{
    //
    //        [self endRefresh];
    //    });
    if ([[USER_DEFAULTS objectForKey:@"isOpenSound"] boolValue]) {//声音开关
        NSString *path = [[NSBundle mainBundle]pathForResource:@"refresh"
                                                        ofType:@"wav"];
        SystemSoundID soundID;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
        AudioServicesPlaySystemSound(soundID); //仅播放音频
    }
    
    strTitle = @"";
    page = 1;

    [self sendRequest];
}



-(void) loadMore
{
    page ++;
    //加载更多
    NSMutableDictionary * dic = [NSMutableDictionary  dictionary];
    dic[@"TagerUserId"] = self.TagerUserId;
    dic[@"userId"] = allConstMemberid;
    dic[@"page"] = @(page);

    [LSHttpTool sendHttpData:@"getCibdList_app_cibd.im" params:dic success:^(id responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        NSDictionary *dataDic = [NSDictionary dictionary];
        //
        //        NSString * jsonStr = [LSHttpTool DataTOjsonString:dicInfo];
        //        NSLog(@"--------------------json:%@",jsonStr);
        
        dataDic = dicInfo[@"data"];
        
        
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
//                self.items = [NSMutableArray array];
            
            if (page == 1) {
                dataArr = nil;
                dataArr = dataDic[@"record"];
                
                
            }else{
                NSArray *arr = dataDic[@"record"];
                
                                NSMutableArray * mtArr = [NSMutableArray array];
                                for (NSDictionary * dict in dataArr) {
                                    [mtArr addObject:dict];
                                }
                                for (NSDictionary * dict in arr) {
                                    [mtArr addObject:dict];
                                }
                                dataArr = nil;
                                dataArr = mtArr;
                
                for (NSDictionary * dict  in arr) {
                    
                    DFTextImageLineItem *textImageItem = [[DFTextImageLineItem alloc] init];
                    textImageItem.itemType = LineItemTypeTextImage;
                    
                    textImageItem.zanCount = dict[@"zanCount"];
                    textImageItem.shareCount = dict[@"shareCount"];
                    textImageItem.commentCount = dict[@"commentCount"];
                    textImageItem.resId = dict[@"Id"];
                    textImageItem.isZan = dict[@"isZan"];
                    textImageItem.userType = dict[@"userType"];
                    textImageItem.authState = dict[@"authState"];
                    
                    if ([dict[@"userType"] isEqualToString:@"3"]) {
                        
                        textImageItem.companyName = dict[@"address"];
                        
                    }else if ([dict[@"userType"] isEqualToString:@"1"]){
                        
                        if (![dict[@"companyUserName"] isEqualToString:@"null"] && ![dict[@"companyUserName"] isEqualToString:@""]) {
                            
                            textImageItem.companyName = dict[@"companyUserName"];
                            
                        }else{
                            
                            textImageItem.companyName = @"";
                            
                        }
                        
                    }else{
                        
                        textImageItem.companyName = @"";
                        
                    }
                    
                    textImageItem.userId = [dict[@"userId"] integerValue];
                    textImageItem.userAvatar = dict[@"headPhoto"];
                    textImageItem.userNick = dict[@"username"];
                    
                    if ([dict[@"posiTionName"] isEqualToString:@""] || [dict[@"posiTionName"] isEqualToString:@"null"]) {
                        textImageItem.title = @"发表了";
                    }else{
                        textImageItem.title = dict[@"posiTionName"];
                    }
                    textImageItem.text = dict[@"content"];
                    NSMutableArray *srcImages = [NSMutableArray array];
                    NSMutableArray *thumbImages = [NSMutableArray array];
                    NSArray * photoArr = dict[@"photos"];
                    
                    for (int i = 0 ; i < photoArr.count; i++) {
                        NSString *str1 = photoArr[i];
                        
                        if (![str1 isEqualToString:Default_Image]) {
                            
                            [srcImages addObject:photoArr[i]];
                            [thumbImages addObject:photoArr[i]];
                            textImageItem.srcImages = srcImages;
                            textImageItem.thumbImages = thumbImages;
                        }
                    }
                    textImageItem.ts = dict[@"createTime"];
                    
                    
                    if (photoArr.count == 1) {
                        //显示单张图片时，固定高度；
                        CGFloat itemH = 160;
                        CGFloat itemW = 0;
                        UIImageView *imageview = [[UIImageView alloc] init];
                        NSURL *url = [NSURL URLWithString:photoArr[0]];
                        [imageview sd_setImageWithURL:url];
                        SDWebImageManager *manager = [SDWebImageManager sharedManager];
                        //判断是否有缓存
                        BOOL existBool = [manager diskImageExistsForURL:url];
                        UIImage *image;
                        if (existBool) {
                            image = [[manager imageCache] imageFromDiskCacheForKey:url.absoluteString];
                        }else{
                            NSData *data = [NSData dataWithContentsOfURL:url];
                            image = [UIImage imageWithData:data];
                        }
                        
                        //根据image的比例来设置高度
                        if (image.size.height) {
                            itemW = image.size.width/image.size.height *itemH;
                            if(itemW >= itemH){
                                itemW = 160;
                                itemH = image.size.height/image.size.width *itemW;
                            }
                        }
                        
                        textImageItem.width = itemW;
                        textImageItem.height = itemH;
                    }
                    
                    [self addItem:textImageItem];
                }
                
            }
            
            
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            
        }else{
            
            [self.tableView reloadData];
            self.tableView.rowHeight = screenH;
        }
        
    } failure:^(NSError *error) {

        [self showSingleIconBubble:@"网路连接错误"];
        
    }];
    [self endLoadMore];
    
}

-(void)sendRequest{
    NSMutableDictionary * dic = [NSMutableDictionary  dictionary];
    dic[@"TagerUserId"] = self.TagerUserId;
    dic[@"userId"] = allConstMemberid;
    dic[@"page"] = @(page);
    dic[@"content"] = strTitle;

    [LSHttpTool sendHttpData:@"getCibdList_app_cibd.im" params:dic success:^(id responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        NSDictionary *dataDic = [NSDictionary dictionary];
        //
        //                NSString * jsonStr = [LSHttpTool DataTOjsonString:dicInfo];
        //                NSLog(@"--------------------json:%@",jsonStr);
        
        dataDic = dicInfo[@"data"];
        
        
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            self.items = [NSMutableArray array];
            
            if (page == 1) {
                dataArr = nil;
                dataArr = dataDic[@"record"];
                
                
            }else{
                NSArray *arr = dataDic[@"record"];
                
                NSMutableArray * mtArr = [NSMutableArray array];
                for (NSDictionary * dict in dataArr) {
                    [mtArr addObject:dict];
                }
                for (NSDictionary * dict in arr) {
                    [mtArr addObject:dict];
                }
                dataArr = nil;
                dataArr = mtArr;
                
            }
            [self initData];
            
        }else{
            if (strTitle) {

                [self showSingleIconBubble:@"未搜索到数据哦"];
            }
            
            self.tableView.rowHeight = screenH;
        }
        
    } failure:^(NSError *error) {

        [self showSingleIconBubble:@"网络连接错误"];
        
    }];
    [self endRefresh];
    [self.tableView.mj_header endRefreshing];
}

#pragma mark - searchbar delegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //    if (dataArr.count != 0) {
    //        dataArr = [NSMutableArray array];
    //        [self.tableView reloadData];
    //    }
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    NSLog(@"%@",searchBar.text);
    
    if (searchBar.text.length == 0) {
        return YES;
    }else {
        page = 1;
        //        [self sendRequest];
        return YES;
    }
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"-----%@",searchBar.text);
    if (searchBar.text.length != 0) {
        [searchBar resignFirstResponder];
        page = 1;
        strTitle = searchBar.text;
        [self sendRequest];
        searchBar.text = @"";
    }
    
}

#pragma mark - alertview
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        //登录
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
        [self presentViewController:loginNAV animated:YES completion:nil];
    }
    
    
}



@end
